// Native
import { join } from 'path';
import sqlite3 from 'sqlite3';
import fs from 'fs';
// Packages
import { BrowserWindow, app, ipcMain, IpcMainEvent } from 'electron';
import isDev from 'electron-is-dev';
import StorageSqlite from './utils/StorageSqlite';
// import Store from 'electron-store'
import NodeCache from 'node-cache';


const height = 600;
const width = 800;

async function createWindow() {
  // 创建浏览器窗口
  const window = new BrowserWindow({
    title: '中控客户端',
    width,
    height,
    // fullscreen: true,
    // 设置为false以使用AppBar
    frame: false,
    show: true,
    resizable: true,
    fullscreenable: true,
    webPreferences: {
      preload: join(__dirname, 'preload.js')
    }
  });

  const port = process.env.PORT || 3000;
  const url = isDev ? `http://localhost:${port}` : join(__dirname, '../src/out/index.html');

  // 加载应用的index.html文件
  if (isDev) {
    window?.loadURL(url);
  } else {
    window?.loadFile(url);
  }
  // 打开开发者工具
  // window.webContents.openDevTools();

  // 为AppBar添加事件监听
  ipcMain.on('minimize', () => {
    // eslint-disable-next-line no-unused-expressions
    window.isMinimized() ? window.restore() : window.minimize();
    // 或者使用以下方式：win.isVisible() ? win.hide() : win.show()
  });
  ipcMain.on('maximize', () => {
    // eslint-disable-next-line no-unused-expressions
    window.isMaximized() ? window.restore() : window.maximize();
  });

  ipcMain.on('close', () => {
    window.close();
  });

  ipcMain.on('WindowClose', (event, data) => {
    console.log(event, data);
  });

  ipcMain.handle('get-user-data-path', () => {
    return app.getPath('userData');
  });
}

async function initDatabase() {
  const userDataPath = app.getPath('userData');
  const databasePath = `${userDataPath}/brain.db`;
  console.log(sqlite3);
  console.log(databasePath);
  if (!fs.existsSync(databasePath)) {
    fs.closeSync(fs.openSync(databasePath, 'w'));
    console.log('Database file created.');
  }
  StorageSqlite.setDatabase(new sqlite3.Database(databasePath));
}

const store = new NodeCache();  

// 当Electron初始化完成并准备创建浏览器窗口时调用此方法
app.whenReady().then(async () => {
  createWindow();

  app.on('activate', () => {
    // 在macOS上，当点击dock图标且没有其他窗口打开时，通常会重新创建一个窗口
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });

  await initDatabase();
  console.log('sqlite initialization finished');
});

// 当所有窗口关闭时退出应用，除非在macOS上，通常应用和菜单栏会保持活动状态，直到用户使用Cmd + Q显式退出
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

// 在这个文件中，你可以包含你的应用程序的其他特定主进程代码
// 你也可以将它们放在单独的文件中并在这里引入

// 监听`message`通道，并将接收到的消息重新发送给渲染进程
ipcMain.on('message', (event: IpcMainEvent, message: any) => {
  console.log(message);
  setTimeout(() => event.sender.send('message', 'hi from electron'), 0);
});

ipcMain.on('echo', (event: IpcMainEvent, message: string) => {
  console.log(`收到消息${message}`);
  event.sender.send('echo', `echo ${message}`);
});

// 创建StorageSqlite实例
const storageSqlite = new StorageSqlite();

// 监听`createUserTable`事件，调用StorageSqlite类的`createUserTable`方法
ipcMain.on('createUserTable', async () => {
  console.log('create user');
  await storageSqlite.createUserTable();
  console.log('create user successfully');
});

// 监听`saveUser`事件，调用StorageSqlite类的`insert`方法来保存用户数据
ipcMain.on('saveUser',async (event: IpcMainEvent, user: any) => {
  console.log(`user is ${JSON.stringify(user)}`);
  event.sender.send('saveUserResponse', `Add User Successfully`);
  const { username, age, city } = user as unknown as { username: string; age: number; city: string };
  await storageSqlite.insert({
    table: 't_user',
    data: {
      username,
      age,
      city
    }
  });
  let stores = store.get('lastUser');
  console.log("loading user from storage");
  console.log(JSON.stringify(stores));
  console.log('user added successfully');
  storageSqlite.find({ table: 't_user', conditions: { username }, limit: 1 }).then((rows) => {
    console.log('rows found');
    console.log(JSON.stringify(rows));
    store.set('lastUser',rows, 5);//设置5秒本地缓存有效期
  });
});